<?php
/**
 * Created by PhpStorm.
 * User: yy
 * Date: 2019/6/24
 * Time: 19:48
 */

namespace app\api\controller;

use app\common\service\lastWeek\LastWeekStrategyAnalysisService;
use think\Db;

# 上周小结-策略分析
class LastWeekStrategyAnalysis extends BaseController
{
    /**
     * 空气质量比较
     * @author yy by 2019/6/29
     */
    public function getAirQualityCompare()
    {
        $param = $this->request->param();
        # 模拟数据
//        $param = ['start_time' => '2019-06-17', 'end_time' => '2019-06-23', 'plan_id' => '1','region_id'=>53, 'station_id' => 0, 'pollutant_name'=>'aqi'];
        $list  = [];
        try {
            $lastWeekControlAnalysisService = new LastWeekStrategyAnalysisService();
            $list                           = $lastWeekControlAnalysisService->getAirQualityCompare($param);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('成功', $list);
    }
    /**
     * aqi空气质量趋势图
     * @author yy by 2019/6/24
     */
    public function getAqiTrend()
    {
        $param = $this->request->param();
        # 模拟数据
//        $param = ['start_time' => '2019-06-17', 'end_time' => '2019-06-23', 'plan_id' => '1','region_id'=>53, 'station_id' => 0];
        $list  = [];
        try {
            $lastWeekControlAnalysisService = new LastWeekStrategyAnalysisService();
            $list                           = $lastWeekControlAnalysisService->getAqiTrend($param);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('成功', $list);
    }

    /**
     * 策略分析-首要污染物
     */
    public function getPrimaryPollutant()
    {
        $param = $this->request->param();
        //日期列表
        $lastYearWeek = self::getDateFromRange($param['start_time'], $param['end_time']);
        $data['date'] = $lastYearWeek;
        //历史同期
        $start_date = date('Y-m-d',strtotime('-1 year',strtotime($param['start_time'])));
        $end_date = date('Y-m-d',strtotime('-1 year',strtotime($param['end_time'])));
        $sql_history = 'select name,value,publish_time from air_quality_station_primary_pollutant_realtime_day where region_id = ? and station_id = ? and publish_time between ? and ?';
        $list_history = Db::query($sql_history,array($param['region_id'],$param['station_id'],$start_date,$end_date));
        if (count($list_history) <= 0) {
            foreach ($lastYearWeek as $k => $v) {
                $data['data'][0][$k] = '';
            }
        } else {
            $newList = [];
            $newDate = [];
            foreach ($list_history as $k => $v) {
                if (date('H',strtotime($v['publish_time'])) == '12') {
                    array_splice($list_history,$k,1);//删除数组元素，索引重组
                } else {
                    $newList[date("m/d", strtotime($v['publish_time']))][] = ['name' => $v['name'], 'value' => $v['value']];
                }
                array_push($newDate,date('m/d',strtotime($v['publish_time'])));
            }
            //处理O3和O3_8H
            foreach ($newList as $k => $v) {
                for ($i=0;$i<count($v);$i++) {
                    foreach ($v as $k2 => $v2) {
                        if (strtoupper($v2['name']) == 'O3' && strtoupper($v[$i]['name']) == 'O3_8H') {
                            array_splice($newList[$k],$i,1);//删除数组元素，索引重组
                        }
                    }
                }
            }
            $temp = [];
            foreach ($newList as $k1 => $v1) {
                $temp[$k1] = count($v1);
            }
            for ($i=0;$i<max($temp);$i++) {
                foreach ($lastYearWeek as $k => $v) {
                    if (in_array($v,$newDate)) {
                        if (isset($newList[$v][$i])) {
                            if (strtoupper($newList[$v][$i]['name']) == 'O3_8H') {
                                $newList[$v][$i]['name'] = 'O3';
                            }
                            if (strtoupper($newList[$v][$i]['name']) == 'PM25') {
                                $newList[$v][$i]['name'] = 'PM2.5';
                            }
                            $newList[$v][$i]['name'] = strtoupper($newList[$v][$i]['name']);
                            if (max($temp) > 1) {
                                $data['data'][0][$i][] = $newList[$v][$i];
                            } else {
                                $data['data'][0][] = $newList[$v][$i];
                            }

                        } else {
                            if (max($temp) > 1) {
                                $data['data'][0][$i][] = ['name'=>'','value'=>''];
                            } else {
                                $data['data'][0][] = ['name'=>'','value'=>''];
                            }

                        }
                    } else {
                        if (max($temp) > 1) {
                            $data['data'][0][$i][] = ['name'=>'','value'=>''];
                        } else {
                            $data['data'][0][] = ['name'=>'','value'=>''];
                        }

                    }
                }
            }
        }
        //同等气象占比最高首要污染物
        //今天之前所有静稳指数
        $sql_index_all = 'select station_id,stable_weather_index_value,publish_time from stable_weather_index_realtime_day_new where station_id = ? and predict_time < ? and publish_time = predict_time';
        $all_index = Db::query($sql_index_all,array($param['station_id'],date('Y-m-d',time())));
        //静稳指数
        $sql_index = 'select station_id,stable_weather_index_value,publish_time from stable_weather_index_realtime_day_new where station_id = ? and predict_time between ? and ? and publish_time = predict_time';
        $list_index = Db::query($sql_index,array($param['station_id'],$param['start_time'],$param['end_time']));
        //所有首要污染物
        $sql_all = 'select station_id,name,value,publish_time from air_quality_station_primary_pollutant_realtime_day';
        $list_all = Db::query($sql_all);
        $newData = [];
        $indexList = [];
        if (count($list_index) >= 1) {
            //小于所显示日期,且所显示日期的静稳指数相等的所有日期
            foreach ($list_index as $k => $v) {
                foreach ($all_index as $a => $b) {
                    if (strtotime($v['publish_time']) > strtotime($b['publish_time']) && $v['stable_weather_index_value'] == $b['stable_weather_index_value']) {
                        $indexList[date('Y-m-d',strtotime($v['publish_time']))][] = $b;
                    }
                }

            }
            //用筛选的静稳指数日期天数对比查询相同日期首要污染物日期
            $pollutantList = [];
            if (!empty($indexList)) {
                foreach ($indexList as $k => $v) {
                    foreach ($v as $k2 => $v2) {
                        foreach ($list_all as $k1 => $v1) {
                            if (date('Y-m-d',strtotime($v2['publish_time'])) == date('Y-m-d',strtotime($v1['publish_time'])) && $v2['station_id'] == $v1['station_id']) {
                                $pollutantList[$k][] = $v1['name'];
                            }
                        }
                    }
                }
            }
            //处理首要污染物占比最高的首要污染物
            $pollutantNew = [];
            if (!empty($pollutantList)) {
                foreach ($pollutantList as $k => $v) {
                    $pollutantNew[$k] = array_count_values($v);
                }

                foreach ($pollutantNew as $k1 => $v1) {
                    foreach ($v1 as $k2 => $v2) {
                        if ($v2 == max($v1)) {
                            $newResult[$k1][] = $k2;
                        }
                    }

                }
                if (!empty($newResult)) {
                    foreach ($newResult as $k => $v) {
                        foreach ($v as $k1 => $v1) {
                            if ($v1 == 'PM2.5') {
                                $v1 = 'pm25';
                            }
                            if ($v1 == 'O3_8H') {
                                $v1 = 'o3_8hour';
                            }
                            //实际
                            $sql = 'select '.strtolower($v1).' from air_quality_station_aqi_realtime_day where region_id = ? and station_id = ? and publish_time = ?';
                            $sql_result = Db::query($sql,array($param['region_id'],$param['station_id'],$k));
                            if (!empty($sql_result)) {
//                                $newData[$k][] = $sql_result[0];
                                if (strtolower($v1) == 'o3_8hour') {
                                    $newData[$k][] = ['name'=>'o3','value'=>$sql_result[0][strtolower($v1)]];
                                } else {
                                    $newData[$k][] = ['name'=>strtolower($v1),'value'=>$sql_result[0][strtolower($v1)]];
                                }

                            }
                            foreach ($newData as $k5 => $v5) {
                                for ($i=0;$i<count($v5);$i++) {
                                    foreach ($v5 as $k6 => $v6) {
                                        foreach ($v6 as $k7 => $v7) {
                                            if (strtoupper($k7) == 'O3' && strtoupper($v5[$i]['name']) == 'O3_8H') {
                                                array_splice($newData[$k5],$i,1);//删除数组元素，索引重组
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if (!empty($lastYearWeek) && !empty($newData)) {
                        foreach ($lastYearWeek as $k => $v) {
                            foreach ($newData as $k1 => $v2) {
                                if ($v == date('m/d',strtotime($k1))) {
                                    $data['data'][1][$k] = ['name'=>strtoupper($v2[0]['name']),'value'=>$v2[0]['value']];
                                } else {
                                    $data['data'][1][$k] = ['name'=>'','value'=>''];
                                }
                            }
                        }
                    } else {
                        foreach ($lastYearWeek as $k => $v) {
                            $data['data'][1][$k] = ['name'=>'','value'=>''];
                        }
                    }

                }
            }
        }

        //预报
        $sql_forecast = 'select name,value,predict_time from air_quality_station_primary_pollutant_forecast_day where region_id = ? and station_id = ? and predict_time between ? and ? and publish_time = predict_time ';
        $list_forecast = Db::query($sql_forecast,array($param['region_id'],$param['station_id'],$param['start_time'],$param['end_time']));
        if (count($list_forecast) <= 0) {
            foreach ($lastYearWeek as $k => $v) {
                $data['data'][2][$k] = '';
            }
        } else {
            $newList1 = [];
            $newDate1 = [];
            foreach ($list_forecast as $k => $v) {
                if (date('H',strtotime($v['predict_time'])) == '12') {
                    array_splice($list_forecast,$k,1);//删除数组元素，索引重组
                } else {
                    $newList1[date("m/d", strtotime($v['predict_time']))][] = ['name' => $v['name'], 'value' => $v['value']];
                }
                array_push($newDate1,date('m/d',strtotime($v['predict_time'])));
            }
            //处理O3和O3_8H
            foreach ($newList1 as $k => $v) {
                for ($i=0;$i<count($v);$i++) {
                    foreach ($v as $k2 => $v2) {
                        if (strtoupper($v2['name']) == 'O3' && strtoupper($v[$i]['name']) == 'O3_8H') {
                            array_splice($newList1[$k],$i,1);//删除数组元素，索引重组
                        }
                    }
                }
            }
            $temp1 = [];
            foreach ($newList1 as $k1 => $v1) {
                $temp1[$k1] = count($v1);
            }
            for ($i=0;$i<max($temp1);$i++) {
                foreach ($lastYearWeek as $k => $v) {
                    if (in_array($v,$newDate1)) {
                        if (isset($newList1[$v][$i])) {
                            if (strtoupper($newList1[$v][$i]['name']) == 'O3_8H') {
                                $newList1[$v][$i]['name'] = 'O3';
                            }
                            if (strtoupper($newList1[$v][$i]['name']) == 'PM25') {
                                $newList1[$v][$i]['name'] = 'PM2.5';
                            }
                            $newList1[$v][$i]['name'] = strtoupper($newList1[$v][$i]['name']);
                            if (max($temp1) > 1) {
                                $data['data'][2][$i][] = $newList1[$v][$i];
                            } else {
                                $data['data'][2][] = $newList1[$v][$i];
                            }

                        } else {
                            if (max($temp1) > 1) {
                                $data['data'][2][$i][] = ['name'=>'','value'=>''];
                            } else {
                                $data['data'][2][] = ['name'=>'','value'=>''];
                            }

                        }
                    } else {
                        if (max($temp1) > 1) {
                            $data['data'][2][$i][] = ['name'=>'','value'=>''];
                        } else {
                            $data['data'][2][] = ['name'=>'','value'=>''];
                        }

                    }
                }
            }
        }

        //实际
        $sql_real = 'select name,value,publish_time from air_quality_station_primary_pollutant_realtime_day where region_id = ? and station_id = ? and publish_time between ? and ?';
        $list_real = Db::query($sql_real,array($param['region_id'],$param['station_id'],$param['start_time'],$param['end_time']));
        if (count($list_real) <= 0) {
            foreach ($lastYearWeek as $k => $v) {
                $data['data'][3][$k] = '';
            }
        } else {
            $newList2 = [];
            $newDate2 = [];
            foreach ($list_real as $k => $v) {
                if (date('H',strtotime($v['publish_time'])) == '12') {
                    array_splice($list_real,$k,1);//删除数组元素，索引重组
                } else {
                    $newList2[date("m/d", strtotime($v['publish_time']))][] = ['name' => $v['name'], 'value' => $v['value']];
                }
                array_push($newDate2,date('m/d',strtotime($v['publish_time'])));
            }
            //处理O3和O3_8H
            foreach ($newList2 as $k => $v) {
                for ($i=0;$i<count($v);$i++) {
                    foreach ($v as $k2 => $v2) {
                        if (strtoupper($v2['name']) == 'O3' && strtoupper($v[$i]['name']) == 'O3_8H') {
                            array_splice($newList2[$k],$i,1);//删除数组元素，索引重组
                        }
                    }
                }
            }
            $temp2 = [];
            foreach ($newList2 as $k1 => $v1) {
                $temp2[$k1] = count($v1);
            }
            for ($i=0;$i<max($temp2);$i++) {
                foreach ($lastYearWeek as $k => $v) {
                    if (in_array($v,$newDate2)) {
                        if (isset($newList2[$v][$i])) {
                            if (strtoupper($newList2[$v][$i]['name']) == 'O3_8H') {
                                $newList2[$v][$i]['name'] = 'O3';
                            }
                            if (strtoupper($newList2[$v][$i]['name']) == 'PM25') {
                                $newList2[$v][$i]['name'] = 'PM2.5';
                            }
                            $newList2[$v][$i]['name'] = strtoupper($newList2[$v][$i]['name']);
                            if (max($temp2) > 1) {
                                $data['data'][3][$i][] = $newList2[$v][$i];
                            } else {
                                $data['data'][3][] = $newList2[$v][$i];
                            }

                        } else {
                            if (max($temp2) > 1) {
                                $data['data'][3][$i][] = ['name'=>'','value'=>''];
                            } else {
                                $data['data'][3][] = ['name'=>'','value'=>''];
                            }

                        }
                    } else {
                        if (max($temp2) > 1) {
                            $data['data'][3][$i][] = ['name'=>'','value'=>''];
                        } else {
                            $data['data'][3][] = ['name'=>'','value'=>''];
                        }

                    }
                }
            }
        }
        $this->success('成功',$data);
    }

    /**
     * 获取指定日期段内每一天的日期
     * @param  Date  $startdate 开始日期
     * @param  Date  $enddate   结束日期
     * @return Array
     */
    function getDateFromRange($startdate, $enddate){
        $stimestamp = strtotime($startdate);
        $etimestamp = strtotime($enddate);
        // 计算日期段内有多少天
        $days = ($etimestamp-$stimestamp)/86400+1;
        // 保存每天日期
        $date = array();
        for($i=0; $i<$days; $i++){
            $date[] = date('m/d', $stimestamp+(86400*$i));
        }
        return $date;
    }
}